package danran.dbapi.service;

import danran.dbapi.domain.ApiAuth;
import danran.dbapi.domain.Token;
import danran.dbapi.mapper.ApiAuthMapper;
import danran.dbapi.mapper.TokenMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @Classname TokenService
 * @Description TODO
 * @Date 2022/1/13 17:36
 * @Created by RanCoder
 */
@Service
public class TokenService {
    @Autowired
    private ApiAuthMapper apiAuthMapper;
    @Autowired
    private TokenMapper tokenMapper;

    /**
     * 将token授权给给定的api组， <strong>如果该token之前已经授权了api组，将会被覆盖</strong>
     * @param tokenId
     * @param groupIds
     */
    @CacheEvict(value = "token_AuthGroups", key = "#tokenId")
    @Transactional
    public void auth(Integer tokenId, String groupIds) {
        apiAuthMapper.deleteByTokenId(tokenId);
        if (!"".equals(groupIds)) {
            Arrays.stream(groupIds.split(",")).forEach(t -> {
                ApiAuth apiAuth = new ApiAuth();
                apiAuth.setTokenId(tokenId);
                apiAuth.setGroupId(t);
                apiAuthMapper.insert(apiAuth);
            });
        }
    }

    @Cacheable(value = "token_AuthGroups", key = "#tokenId", unless = "#result == null")
    public List<String> getAuthGroups(Integer tokenId) {
        return apiAuthMapper.selectByTokenId(tokenId);
    }

    @Cacheable(value = "token", key = "#tokenStr", unless = "#result == null")
    public Token getToken(String tokenStr) {
        return tokenMapper.selectByToken(tokenStr);
    }

    @Transactional
    public void insert(Token token) {
        tokenMapper.insert(token);
    }

    @Transactional
    @CacheEvict(value = "token_AuthGroups", key = "#tokenId")
    public void deleteById(Integer tokenId) {
        tokenMapper.deleteById(tokenId);
    }

    public List<Token> getAll() {
        return tokenMapper.selectList(null);
    }

}
